﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Reflection;

namespace Framework.Network
{
    public sealed partial class NetworkManager : FrameworkModule
    {
        public IMessagePacker MessagePacker { get; set; }
        public Session Session { get; set; }

        private TcpService m_Service;
        private readonly Dictionary<int, Session> m_Id2Session = new Dictionary<int, Session>();
        
        public override void Init()
        {
            this.MessagePacker = new ProtobufPacker();
            this.m_Service = new TcpService(Packet.PacketSizeLength2) { Parent = this };
            
            this.InitOpcodeType();
            this.InitDispatcher();
        }

        public override bool NeedUpdate
        {
            get
            {
                return true;
            }
        }

        public override void Update(float elapseSeconds, float realElapseSeconds)
        {
            base.Update(elapseSeconds, realElapseSeconds);
            this.m_Service.Update();
        }

        public void Remove(int id)
        {
            Session session;
            if (this.m_Id2Session.TryGetValue(id, out session))
            {
                return;
            }
            this.m_Id2Session.Remove(id);
            session.Dispose();
        }

        public Session Create(string address)
        {
            BaseChannel channel = this.m_Service.ConnectChannel(address);
            Session session = new Session(channel) { Parent = this };
            this.m_Id2Session.Add(session.Id, session);
            session.Start();
            return session;
        }
    }
}


